//
//  ScanQRController.m
//  iOS_ChenQiang
//
//  Created by 陈强 on 16/5/20.
//  Copyright © 2016年 chenqiang1202. All rights reserved.
//

#import "ScanQRController.h"
#import <AVFoundation/AVFoundation.h>

@interface ScanQRController ()<AVCaptureMetadataOutputObjectsDelegate>{
    
    __weak IBOutlet UIView *_cameraV;
    UIImageView *_scanLine;
}
@property (strong, nonatomic) NSTimer              *timerScan;
@property ( strong , nonatomic) AVCaptureDevice * device;
@property ( strong , nonatomic) AVCaptureDeviceInput * input;
@property (strong, nonatomic) AVCaptureSession           *session;
@property (strong, nonatomic) AVCaptureVideoPreviewLayer *previewLayer;
@property (strong, nonatomic) AVCaptureMetadataOutput *output;
@end

@implementation ScanQRController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self startScanning];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self stopScanning];
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//    [self configSession];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = @"扫一扫";
    
    _scanLine = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"QRCodeScanLine"]];
    [_cameraV addSubview:_scanLine];
    
    [self configSession];
}

- (AVCaptureDevice *)device
{
    if (_device == nil) {
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
    return _device;
}

- (AVCaptureDeviceInput *)input
{
    if (_input == nil) {
        _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    }
    return _input;
}

- (AVCaptureSession *)session
{
    if (_session == nil) {
        _session = [[AVCaptureSession alloc] init];
    }
    return _session;
}

- (AVCaptureVideoPreviewLayer *)previewLayer
{
    if (_previewLayer == nil) {
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    }
    return _previewLayer;
}

- (AVCaptureMetadataOutput *)output
{
    if (_output == nil) {
        _output = [[AVCaptureMetadataOutput alloc] init];
        
        // 1.获取屏幕的frame
        CGRect viewRect = self.view.frame;
        // 2.获取扫描容器的frame
        CGRect containerRect = _cameraV.frame;
        
        CGFloat x = containerRect.origin.y / viewRect.size.height;
        CGFloat y = containerRect.origin.x / viewRect.size.width;
        CGFloat width = containerRect.size.height / viewRect.size.height;
        CGFloat height = containerRect.size.width / viewRect.size.width;
        
        // CGRect outRect = CGRectMake(x, y, width, height);
        // [_output rectForMetadataOutputRectOfInterest:outRect];
        _output.rectOfInterest = CGRectMake(x, y, width, height);
    }
    return _output;
}

- (void)configSession {
    // 1.判断输入能否添加到会话中
    if (![self.session canAddInput:self.input]) return;
    [self.session addInput:self.input];
    
    // 2.判断输出能够添加到会话中
    if (![self.session canAddOutput:self.output]) return;
    [self.session addOutput:self.output];
    
    // 4.设置输出能够解析的数据类型
    // 注意点: 设置数据类型一定要在输出对象添加到会话之后才能设置
    self.output.metadataObjectTypes = self.output.availableMetadataObjectTypes;
    
    // 5.设置监听监听输出解析到的数据
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 6.添加预览图层
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];
    self.previewLayer.frame = [UIScreen mainScreen].bounds;
   
}

- (void)startScanning {
    if (![self.session isRunning]) {
        [self.session startRunning];
    }
    
    if (_timerScan) {
        [_timerScan invalidate];
        _timerScan = nil;
    }
    
    self.timerScan = [NSTimer timerWithTimeInterval:2.f target:self selector:@selector(scanAnimate) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop]addTimer:self.timerScan forMode:NSRunLoopCommonModes];
    [self.timerScan fire];
}

- (void)stopScanning {
    if ([self.session isRunning]) {
        [self.session stopRunning];
    }
    if (_timerScan) {
        [_timerScan invalidate];
        _timerScan = nil;
    }
}

- (void)scanAnimate {
    _scanLine.frame = CGRectMake(0, 0, _cameraV.frame.size.width, 12);
    [UIView animateWithDuration:2 animations:^{
      _scanLine.frame = CGRectMake(0, CGRectGetHeight(_cameraV.frame), _cameraV.frame.size.width, 12);
    }];
}

#pragma mark - AVCaptureMetadataOutputObjects Delegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    for(AVMetadataObject *current in metadataObjects) {
        if ([current isKindOfClass:[AVMetadataMachineReadableCodeObject class]]
            && [current.type isEqualToString:AVMetadataObjectTypeQRCode])
        {
            NSString *scannedResult = [(AVMetadataMachineReadableCodeObject *) current stringValue];
            
//            [self stopScanning];
            //1.拿到数据scannedResult
            //2.停止扫描，跳转界面
            
            NSLog(@"扫描结果 = %@",scannedResult);
            break;
        }else{
            NSLog(@"获取错误");
        }
    }
}
@end
